#include "app_mqtt.h"

MQTTClient client;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
// 接受到数据的回调函数
mqtt_rec_callback rec_callback = NULL;
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    (void)context;
    printf("Message with token value %d delivery confirmed\n", dt);
}

/**
 * @brief 接收到数据的回调函数
 * @return int 1:成功 others:失败
 */
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    (void)context;
    (void)topicLen;
    int result = 0; 
    printf("Message arrived\n");
    printf("     topic: %s\n", topicName);
    // printf("   message: %.*s\n", message->payloadlen, (char *)message->payload);
    if (rec_callback != NULL)
    {
         result = rec_callback((char *)message->payload)?1:0;
    }
    
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

void connlost(void *context, char *cause)
{
    (void)context;
    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);
}

int app_mqtt_init(void)
{
    // 1. 创建客户端
    if ((MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        perror("Failed to create client\n");
        return -1;
    }
    // 2. 设置回调函数
    if ((MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
    {
        perror("Failed to set callbacks\n");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 3. 连接服务器
    if ((MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        perror("Failed to connect\n");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 4. 订阅主题
    if ((MQTTClient_subscribe(client, TOPIC_PULL, QOS)) != MQTTCLIENT_SUCCESS)
    {
        perror("Failed to subscribe\n");
        MQTTClient_disconnect(client, 10000);
        MQTTClient_destroy(&client);
        return -1;
    }
    //5.设置QOS
    pubmsg.qos = QOS;
    log_debug("MQTT init success\n");
    return 0;
}

int app_mqtt_send(char *json)
{
    // 1. 填充消息
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    if ((MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, NULL)) != MQTTCLIENT_SUCCESS)
    {
        perror("Failed to publish message\n");
        return -1;
    }
    return 0;
}

int app_mqtt_close(void)
{
    // 1. 取消订阅主题
    if ((MQTTClient_unsubscribe(client, TOPIC_PULL)) != MQTTCLIENT_SUCCESS)
    {
        perror("Failed to unsubscribe\n");
        return -1;
    }
    // 2. 断开连接
    if ((MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to disconnect\n");
        return -1;
    }
    // 3. 销毁客户端
    MQTTClient_destroy(&client);
    return 0;
}

void app_mqtt_register_recv_callback(mqtt_rec_callback callback)
{
    rec_callback = callback;
}